<?php

namespace app\admin\controller\qingdongwms\examine;

use addons\qingdongwms\model\Achievement;
use addons\qingdongwms\model\Contract;
use addons\qingdongwms\model\ContractProduct;
use addons\qingdongwms\model\Customer;
use addons\qingdongwms\model\DeliveryProduct;
use addons\qingdongwms\model\Flow;
use addons\qingdongwms\model\Message;
use addons\qingdongwms\model\Order;
use addons\qingdongwms\model\PartsStock;
use addons\qingdongwms\model\PartsStockReload;
use addons\qingdongwms\model\ProductWarehouse;
use addons\qingdongwms\model\Quote;
use addons\qingdongwms\model\Staff;
use addons\qingdongwms\model\ExamineRecord as ExamineRecordModel;
use addons\qingdongwms\model\BusinessStatus;
use addons\qingdongwms\model\Business;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Invoice;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 审批记录
 */
class ExamineRecord extends Base {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];

    /**
     * 审核
     */
	public function examine() {
		$relation_type = input('relation_type');
		$relation_id   = input('relation_id');
		$content       = input('content','');
		$status        = input('status');
        $record = ExamineRecordModel::where([
            'relation_type' => $relation_type,
            'relation_id' => $relation_id,
            'status' => 0,
            'check_staff_id' => $this->_staff->id
        ])->find();
        if (empty($record)) {
            $this->error('没有待审核数据');
        }
        if ($this->request->isAjax()) {
            $staff = Staff::info();
            Db::startTrans();
            try {
                $model = new ExamineRecordModel();
                if ($model->isUpdate(true)->save([
                        'status' => $status,
                        'content' => $content,
                        'check_time' => time()
                    ], ['id' => $record['id']]) == false) {
                    throw new Exception('修改失败');
                }
                switch ($relation_type) {
                    case $model::CONSUME_TYPE://费用
                        $rowModel = new \addons\qingdongwms\model\Consume();
                        $row = $rowModel->where(['id' => $relation_id])->find();
                        break;
                    case $model::CONTRACT_TYPE://合同
                        $rowModel = new \addons\qingdongwms\model\Contract();
                        $row = $rowModel->where(['id' => $relation_id])->find();
                        break;
                    case $model::RECEIVABLES_TYPE://回款
                        $rowModel = new \addons\qingdongwms\model\Receivables();
                        $row = $rowModel->where(['id' => $relation_id])->find();
                        break;
                    case $model::ACHIEVEMENT_TYPE://业绩目标
                        $rowModel = new \addons\qingdongwms\model\AchievementRecords();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        break;
                    case $model::APPROVAL_TYPE://审批
                        $rowModel = new \addons\qingdongwms\model\Approval();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        $row['staff_id'] = $row['create_staff_id'];
                        break;
                    case $model::PARTS_TYPE://零件
                        $rowModel = new PartsStockReload();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        $row['staff_id'] = $row['create_staff_id'];
                        break;
                    case $model::QUOTE_TYPE://报价单
                        $rowModel = new Quote();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        $row['staff_id'] = $row['create_staff_id'];
                        break;
                    case $model::INVOICE_TYPE://发票
                        $rowModel = new Invoice();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        $row['staff_id'] = $row['create_staff_id'];
                        break;
                    case $model::DELIVERY_TYPE://发货单
                        $rowModel = new \addons\qingdongwms\model\Delivery();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        break;
                    case $model::INSTOCK_TYPE://入库单
                        $rowModel = new \addons\qingdongwms\model\Instock();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        break;
                    case $model::OUTSTOCK_TYPE://出库单
                        $rowModel = new \addons\qingdongwms\model\Outstock();
                        $row = $rowModel->where(['id' => $relation_id])->find()->toArray();
                        break;
                    default:
                        throw new Exception('参数错误');
                }
                if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $record['id'], 'to_staff_id' => $this->auth->id])->find()) {
                    Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
                }
                $check_staff_ids = explode(',', trim($row['check_staff_ids'], ','));
                $check_staff_ids[] = $staff->id;
                if ($status == 1) {//审核通过
                    $flow = Flow::getstepdetail($relation_type, $relation_id);
                    //给下一审核人发送通知
                    $result = Flow::sendStepRecord($flow, $relation_type, $relation_id, $check_staff_ids, $staff->id);

                    //已完成审核
                    if ($result['status'] == true) {
                        $rowModel->save([
                            'check_status' => 2,
                            'check_staff_ids' => implode(',', $check_staff_ids),
                            'order_id' => $result['order_id']
                        ], ['id' => $relation_id]);
                        switch ($relation_type) {
                            case $model::CONTRACT_TYPE://合同
                                Customer::where(['id' => $row['customer_id']])->update(['contract_status' => 1]);
                                //合同签署成功后商机变为赢单
                                if ($row['business_id']) {
                                    BusinessStatus::create(['business_id' => $row['business_id'], 'type' => 4, 'remark' => '合同签署']);
                                    Business::where(['id' => $row['business_id']])->update(['contract_status' => 1, 'updatetime' => time()]);
                                }
                                $customerUpdate = ['contract_status' => 1, 'trade_date' => date('Y-m-d')];
                                $customerInfo = Customer::where(['id' => $row['customer_id']])->find();
                                if (!in_array($customerInfo['follow'], ['已经购买'])) {
                                    $customerUpdate['follow'] = '准备付款';
                                }
                                Customer::where(['id' => $row['customer_id']])
                                    ->update($customerUpdate);

                                $orderModel = new Order();
                                $order = [
                                    'customer_id' => $row['customer_id'],
                                    'contacts_id' => $row['contacts_id'],
                                    'contract_id' => $row['id'],
                                    'create_staff_id' => $row['owner_staff_id'],
                                    'owner_staff_id' => $row['owner_staff_id'],
                                ];
                                $orderModel->isUpdate(false)->save($order);
                                $order_id = $orderModel->getLastInsID();

                                break;
                            case $model::ACHIEVEMENT_TYPE://业绩目标
                                $m = new Achievement();
                                $m->where(['type' => $row['type'], 'status' => $row['status'], 'obj_id' => $row['obj_id']])->delete();
                                unset($row['id']);
                                unset($row['createtime']);
                                unset($row['updatetime']);
                                unset($row['deletetime']);
                                $m->allowField(true)->save($row);
                                $row['staff_id'] = $row['obj_id'];
                                break;
                            case $model::RECEIVABLES_TYPE://回款
                                $m = new Contract();
                                $contract = $m->where(['id' => $row['contract_id']])->with(['receivables'])->find();

                                if (!empty($contract['receivables']) && $contract['receivables']['repayment_money'] >= $contract['money']) {
                                    Customer::where(['id' => $row['customer_id']])->update(['follow' => '已经购买']);
                                    $m->save(['contract_status' => 1], ['id' => $row['contract_id']]);//已完成
                                }
                                break;
                            case $model::PARTS_TYPE://零件出入库

                                $parts = $row['parts'];
                                $add = [
                                    'type' => $row['type'],
                                    'odd_numbers' => $row['odd_numbers'],
                                    'storage_time' => $row['storage_time'],
                                    'desc' => $row['desc'],
                                    'create_staff_id' => $row['create_staff_id'],
                                ];
                                foreach ($parts as $v) {
                                    $add['parts_id'] = $v['id'];
                                    $add['number'] = $v['number'];
                                    PartsStock::addStock($add);
                                }
                                break;
                            case $model::QUOTE_TYPE:
                                Quote::where(['id' => $row['id']])->update([
                                    'status' => 1]);
                                break;
                            case $model::INSTOCK_TYPE://入库单
                                $instockProduct=new \addons\qingdongwms\model\InstockProduct();
                                $products = $instockProduct->where([
                                    'instock_id' => $row['id']
                                ])->select();

                                foreach ($products as $p) {
                                    //入库
                                    ProductWarehouse::instock($row['warehouse_id'],$p['product_id'],$p['number']);
                                }
                                break;
                            case $model::DELIVERY_TYPE://发货单
                                $deliveryProduct = new DeliveryProduct();
                                $products = $deliveryProduct->where([
                                    'delivery_id' => $row['id']
                                ])->select();
                                $cProducts=ContractProduct::where(['contract_id' => $row['contract_id']])
                                    ->column('product_id,number,ship_number','id');
                                $contract_ship_status=1;//已发货
                                foreach ($products as $p) {
                                    if ($p['contract_product_id']) {
                                        if (isset($cProducts[$p['contract_product_id']])) {
                                            $cPro = $cProducts[$p['contract_product_id']];
                                            $ship_status = 0;
                                            $number = $p['number'] + $cPro['ship_number'];
                                            if ($number >= $cPro['number']) {
                                                $ship_status = 1;
                                            }
                                            if($ship_status == 0){
                                                $contract_ship_status=6;//分批发货中
                                            }
                                            $contractProduct = new ContractProduct();
                                            $contractProduct->save([
                                                'ship_status' => $ship_status,
                                                'ship_number' => $number
                                            ], ['id' => $p['contract_product_id']]);
                                        }
                                    }
                                    //出库
                                    ProductWarehouse::outstock($row['warehouse_id'],$p['product_id'],$p['number']);
                                }
                                Contract::where(['id'=>$row['contract_id']])
                                    ->update(['ship_status'=>$contract_ship_status]);
                                break;
                            case $model::OUTSTOCK_TYPE://商品出库单
                                $outstockGood=new \addons\qingdongwms\model\OutstockGood();
                                $products = $outstockGood->where([
                                    'relation_id' => $row['id']
                                ])->select();

                                foreach ($products as $p) {
                                    //出库
                                    ProductWarehouse::goodoutstock($row['warehouse_id'],$p['goods_id'],$p['number']);
                                }
                                break;
                        }
                        Message::addMessage(Message::EXAMINE_ADOPT_TYPE, $record['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id);

                        //删除 或签的待审批通知
                        Message::setRead(Message::EXAMINE_TYPE, $record['id']);
                        ExamineRecordModel::where([
                            'relation_type' => $relation_type,
                            'relation_id' => $relation_id,
                            'status' => 0,
                        ])->update(['status' => 3, 'check_time' => time()]);
                    } else {
                        $rowModel->save([
                            'check_staff_ids' => implode(',', $check_staff_ids),
                            'order_id' => $result['order_id']
                        ], ['id' => $relation_id]);
                    }
                } else {
                    //审核未通过
                    $rowModel->save(['check_status' => 3, 'check_staff_ids' => ''], ['id' => $relation_id]);
                    Message::addMessage(Message::EXAMINE_REFUSE_TYPE, $record['id'], $row['owner_staff_id'] ?? $row['staff_id'], $staff->id, '');

                    //删除待审批通知
                    $ids = ExamineRecordModel::where([
                        'relation_type' => $relation_type,
                        'relation_id' => $relation_id,
                        'status' => 0,
                    ])->column('id');
                    Message::where(['relation_type' => Message::EXAMINE_TYPE, 'relation_id' => ['in', $ids], 'status' => 0])->update(['read_time' => time(), 'status' => 1]);

                    ExamineRecordModel::where([
                        'relation_type' => $relation_type,
                        'relation_id' => $relation_id,
                        'status' => 0,
                    ])->update(['status' => 3, 'check_time' => time()]);
                }


                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                Log::record($e->getMessage());
                $this->error($e->getMessage());
            }

            $this->success('审核成功');
        }


        $this->assign('relation_type',$relation_type);
        $this->assign('relation_id',$relation_id);
        $this->assign('status',$status);
        return $this->view->fetch();
	}

}
